package com.lkd.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkd.entity.Business;
import com.lkd.entity.Node;
import com.lkd.entity.Region;
import com.lkd.entity.VendingMachine;
import com.lkd.mapper.BusinessMapper;
import com.lkd.mapper.NodeMapper;
import com.lkd.mapper.RegionMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.service.NodeService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.vo.NodeVo;
import com.lkd.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 点位表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-20
 */
@Service
public class NodeServiceImpl extends ServiceImpl<NodeMapper, Node> implements NodeService {

    @Autowired
    private VendingMachineMapper vendingMachineMapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Override
    public PageBean<NodeVo> findNodeByPage (Long regionId, Integer pageIndex, Integer pageSize) {
        Page<Node> page = new Page<> (pageIndex, pageSize);

        LambdaQueryWrapper<Node> wrapper = new LambdaQueryWrapper<> ();
        wrapper.like (regionId!=null, Node::getRegionId, regionId);

        page = getBaseMapper ().selectPage (page, wrapper);

        List<NodeVo> list = page.getRecords ().stream ().map (node -> {

        NodeVo nodeVo = BeanUtil.copyProperties (node,NodeVo.class);


        //连接region
        LambdaQueryWrapper<Region> wrapper1 = new LambdaQueryWrapper<> ();
        wrapper1.eq (node.getRegionId ()!=null,Region::getId,node.getRegionId ());
        nodeVo.setRegion (regionMapper.selectOne (wrapper1));

        //连接商品表
        LambdaQueryWrapper<Business> wrapper2 = new LambdaQueryWrapper<> ();
        wrapper2.eq (node.getBusinessId ()!=null,Business::getId,node.getBusinessId ());
        nodeVo.setBusinessType (businessMapper.selectOne (wrapper2));

        //获取VmCount 同时 连接machine表
        LambdaQueryWrapper<VendingMachine> wrapper3 = new LambdaQueryWrapper<> ();
        wrapper3.eq (node.getId ()!=null,VendingMachine::getOwnerId, node.getId ());
//                .eq (StrUtil.isNotEmpty (),VendingMachine::getNodeId,node.getId ());
        nodeVo.setVmCount (vendingMachineMapper.selectCount (wrapper3));

        return nodeVo;
        }).collect (Collectors.toList ());

        return new PageBean<> (page,list);

    }
}
